I'm trying to import myArr from hello.js into index.js. However I get an error of
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
File hello.js
export let myArr = ['hello', 'hi', 'hey'];
File index.js
import { myArr } from './hello.js';
console.log(myArr);
Where am I going wrong?
The problem is that Node.js does not currently support import and export natively yet. It is still experimental according to the documentation. I recommend you use Babel to compile your code and allow you to use import and export.
For example, you can install the @babel/node package and run your project using:
npx babel-node index.js
Here are the documentation for @babel/node. Like the documentation state, this command is only meant for local development. In production, they recommend a configuration like this.
I ran your code without any problems. Check for two things:
package.json includes a line for "type": "module". Without this line, Node.js assumes you want to use CommonJS modules rather than ESM.If you have Node.js version lower than 14, e.g., v12 - you must specify this flag:
node --experimental-modules your.mjs
I ran into a similar issue while building my React project.
Here's the error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/pradeep/Work/my_project/node_modules/@babel/runtime/helpers/interopRequireWildcard/_index.mjs
Then I realized that I am on a different Node.js version than the one used to install packages in this project.
I had two options:
I chose the first approach and it worked for me.
I use nvm to install the latest stable version of Node.js.
To delete the package-lock.json file and the node_modules folder, run npm. I then npm start to solve my problem.